package com.tchhy.mvplibrary.rx

import android.app.Service
import android.content.Intent
import com.google.gson.Gson
import com.tchhy.basemodule.basedata.TokenHelper
import com.tchhy.basemodule.basedata.UserInfoHelper
import com.tchhy.basemodule.utils.MedicineUsageNoticeClearUtil
import com.tchhy.basemodule.utils.SystemUtils
import com.tchhy.mvplibrary.BuildConfig
import com.tchhy.provider.data.common.BaseResp
import com.tchhy.provider.data.common.EmptyResp
import com.tchhy.toast.ToastUtils
import com.trello.rxlifecycle2.LifecycleProvider
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import retrofit2.HttpException

/**
 * Describe: RxJava线程戏相关
 *
 */
open class ServiceObserver<T>(
    var context: Service,
    val lifecycleProvider: LifecycleProvider<*>,
    private val onSuccess: (T) -> Unit
) : Observer<BaseResp<T>> {

    open fun onErrorMessage(errorMessage: String) {
        ToastUtils.show(errorMessage)
    }

    open fun onErrorMessage(code: Int,errorMessage: String) {
        ToastUtils.show(errorMessage)
    }

    open fun onOtherCode(code: Int, data: T?) {

    }

    override fun onNext(t: BaseResp<T>) {
        if (t.status == 0) {
            if (t.data != null) {
                onSuccess.invoke(t.data!!)
            } else {
                onDataNull()
            }
        } else {
            onOtherCode(t.status, t.data)
            onErrorMessage(t.status,t.message)
        }
    }

    open fun onDataNull() {
    }

    override fun onComplete() {
    }

    override fun onSubscribe(d: Disposable) {
    }

    override fun onError(e: Throwable) {
        if (e is HttpException) {
            val errorBody = e.response()?.errorBody()?.string()
            try {
                val emptyResponse = Gson().fromJson(errorBody, EmptyResp::class.java)
                when (emptyResponse.status) {
                    ServiceCodeEnum.CODE_ACCESS_TOKEN_EXPIRED,
                    ServiceCodeEnum.CODE_ACCESS_TOKEN_VALIDATE_ERROR,
                    ServiceCodeEnum.CODE_ACCESS_REFRESH_TOKEN_VALIDATE_ERROR -> {
                        jumpToLoginActivity()
                    }
                    ServiceCodeEnum.CODE_LIMIT -> {
                        jumpToAbnormalActivity()
                    }
                }
                if (BuildConfig.DEBUG) { //是否是正式服务器
                    ToastUtils.show("接口异常：响应码：" + e.code() + "\n原因：" + emptyResponse.message)
                } else {
                    ToastUtils.show(emptyResponse.message + "")
                }
            } catch (e: Exception) {
                ToastUtils.show("网络连接不稳定，请稍后再试")
            }
        } else {
            ToastUtils.show("网络连接不稳定，请稍后再试")
            //ToastUtils.show("服务器错误：\n原因：" + RxErrorHandle(e).error())
        }
    }

    private fun jumpToLoginActivity() {
        val clz = Class.forName("com.tchhy.tcjk.ui.login.activity.LoginNewActivity")
        val intent = Intent(context, clz)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        UserInfoHelper.clearAccountInfo(context)
        TokenHelper.clearAuthorization(context)
        MedicineUsageNoticeClearUtil.cancelAllTask()
        context.startActivity(intent)
    }

    private fun jumpToAbnormalActivity() {
        val clz = Class.forName("com.tchhy.tcjk.ui.abnormal.AbnormalActivity")
        val intent = Intent(context, clz)
        intent.putExtra("accessName", SystemUtils.getTopActivity(context))
        context.startActivity(intent)
    }
}